# -*- coding: utf-8 -*-
import simplejson
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from press.form import RegisterForm, ArticleForm, RegisterAdminForm, HeadlineForm
from django.core.urlresolvers import reverse
from press.models import  Register, Article, Category, Headline
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.core import mail
from django.db import transaction
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from datetime import date, datetime
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import settings
import re
QUOTA = 40
QUOTA_HEADLINE = 10

def update_ajax(request):
    if request.method == 'POST':
        if request.is_ajax():
            last_request = request.COOKIES.get('time')
            try:
                tmp = re.findall(r'\d+', last_request)
                tmp2 = [int(i) for i in tmp]
                last_request = datetime(tmp2[0], tmp2[1], tmp2[2], tmp2[3], tmp2[4], tmp2[5])
                posts = Article.objects.filter(status = 1, post_date__gt = last_request, post_date__lt = datetime.now()).order_by('-post_date')

                return_post = []
                for post in posts:
                    new_dict = {'id': post.id, 'title' : post.title}
                    return_post.append(new_dict)

                if len(posts):
                    time = posts[0].post_date
                else:
                    time = last_request

                headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
                return_headlines = u".....".join([headline.title for headline in headlines])

                if len(headlines):
                    time = max(headlines[0].show_date, time)

                data = simplejson.dumps({'time': str(time), 'posts' : return_post, 'headlines' : return_headlines})
                print data
                response = HttpResponse(data, mimetype='json')
                response.set_cookie("time", time)
                return response
            except Exception as e:
                print e
def user_login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index'))
    if request.method == 'POST':
        # validate the form
        form = AuthenticationForm(data=request.POST)
        print form.errors
        if form.is_valid():
            # log the user in
            login(request, form.get_user())
            return HttpResponseRedirect(reverse('index'))
    else:
        form = AuthenticationForm(request)

    context = RequestContext(request)
    response = render_to_response('login.html', {'form': form}, context_instance=context)
    return response


def index(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    request_date = date.today()
    posts = Article.objects.filter(post_date__year = request_date.year,
        post_date__month = request_date.month,
        post_date__day = request_date.day,
        status = 1, post_date__lt = datetime.now()).order_by('-post_date')
    paginator = Paginator(posts, QUOTA) # Show QUOTA posts per page
    page = request.GET.get('page')
    try:
        return_posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        return_posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        return_posts = paginator.page(paginator.num_pages)
    categories = Category.objects.all().order_by("order", "name")
    cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
    print cat_menu
    headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
    return_headlines = u".....".join([headline.title for headline in headlines])
    context = RequestContext(request)

    response = render_to_response('index.html', {'posts': return_posts, 'categories' : categories, 'menu' : cat_menu, 'headlines' : return_headlines}, context_instance=context)
    response.set_cookie("time",datetime.now())
    return response
#
#def register(request):
#    if request.user.is_authenticated():
#        return HttpResponseRedirect(reverse('index'))
#    else:
#        message = ''
#        # test new brance
#        register_form = RegisterForm()
#        success = True
#        if request.method == 'POST':
#            data = request.POST.copy()
#            register_form = RegisterForm(data=data)
#            if register_form.is_valid():
#                register_form.save()
#                message = u'Bạn đã đăng ký thành công. \
#                            Tài khoản của bạn sẽ được chúng tôi kích hoạt sớm nhất có thể.'
#                register_form = RegisterForm()
#            else:
#                message = u"Có lỗi ở thông tin nhập vào"
#
#        context = RequestContext(request)
#        return render_to_response('register.html',
#                {'message': message,
#                 'form': register_form},
#            context_instance=context)
#
#
#def extract_fullname(name):
#    eles = [e.capitalize() for e in name.split(' ') if e]
#    if not eles: raise Exception('BadName')
#    firstname = eles[-1]
#    lastname = ''
#    if len(firstname) == 1 and len(eles) >= 2:
#        firstname = ' '.join(eles[-2:])
#        lastname = ' '.join(eles[:-2])
#    else:
#        firstname = eles[-1]
#        lastname = ' '.join(eles[:-1])
#    return firstname, lastname
#
#
#def _send_email(subject, message, from_addr=None, to_addr=[]):
#    mail.send_mail(settings.EMAIL_SUBJECT_PREFIX + subject,
#        message,
#        settings.EMAIL_HOST_USER,
#        to_addr)
#
#
#def send_email(subject, message, from_addr=None, to_addr=[]):
#    _send_email(subject, message, from_addr, to_addr)
#
#
#def activate_user(reg_user):
#    if not request.user.is_authenticated():
#        return HttpResponseRedirect(reverse('index'))
#    if not request.user.is_superuser:
#        return HttpResponseRedirect(reverse('index'))
#
#    if type(reg_user) != Register:
#        raise Exception("Bad request")
#    first_name, last_name = extract_fullname(reg_user.register_name)
#
#    user = User.objects.create(
#        username=reg_user.user_name,
#        password=make_password(reg_user.user_name),
#        first_name=first_name,
#        last_name=last_name,
#        email=reg_user.register_email)
#    new_account = Account()
#    new_account.user_id = user
#    new_account.save()
#    subject = u'Kích hoạt tài khoản tại Link Tài chính'
#    message = u'Tài khoản tại địa chỉ: http://www.linktaichinh.com của bạn là:\nTên đăng nhập: %s\nMật khẩu: %s\nXin cảm ơn.' % (
#    unicode(reg_user.user_name),
#    unicode(reg_user.user_name))
#    send_email(subject, message, to_addr=[reg_user.register_email])
#
#
#@transaction.commit_on_success
#def activate(request):
#    if not request.user.is_authenticated():
#        return HttpResponseRedirect(reverse('index'))
#    if not request.user.is_superuser:
#        return HttpResponseRedirect(reverse('index'))
#    message = ''
#    reg_list = Register.objects.filter(status__exact='CHUA_CAP').order_by('register_name')
#
#    if request.method == 'POST':
#        status_list = request.POST.getlist('status')
#        print status_list
#        for reg, form in zip(reg_list, status_list):
#            if form == u'DA_CAP':
#                if not len(message):
#                    message = u'Đã kích hoạt tài khoản: '
#                reg.status = 'DA_CAP'
#                print reg.status
#                activate_user(reg)
#                reg.save()
#                print reg.status
#                message += unicode(reg.user_name) + u', '
#
#    reg_list = Register.objects.filter(status__exact='CHUA_CAP').order_by('register_name')
#    reg_form_list = []
#    i = 0
#    for reg in reg_list:
#        reg_form_list.append(RegisterAdminForm())
#        reg_form_list[i] = RegisterAdminForm(instance=reg)
#        i += 1
#
#    list = zip(reg_list, reg_form_list)
#    context = RequestContext(request)
#    return render_to_response('activate.html',
#            {'message': message,
#             'list': list},
#        context_instance=context)
#
#
#def new_article(request):
#    if not request.user.is_authenticated():
#        return HttpResponseRedirect(reverse('index'))
#    message = ''
#    article_form = ArticleForm()
#    if request.method == 'POST':
#        data = request.POST.copy()
#        article_form = ArticleForm(data=data)
#        if article_form.is_valid():
#            article = article_form.save(commit=False)
#            article.written_date = datetime.now()
#            article.account_id = Account.objects.get(user_id = request.user)
#            article.save()
#            return HttpResponseRedirect(reverse("view_single_article", args=[article.id]))
#        else:
#            message = u'Có lỗi ở dữ liệu nhập vào.'
#
#    context = RequestContext(request)
#    categories = Category.objects.all().order_by("order", "name")
#    cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
#    return render_to_response('new_article.html',
#            {'message': message,
#             'categories' : categories,
#             'menu' : cat_menu,
#             'form': article_form},
#        context_instance=context)


def edit_article(request, article_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index'))

    try:
        seleted_article = Article.objects.get(id=article_id, status = 1)
    except Exception as e:
        raise Exception("Bad request Exception")
    message = u''
    article_form = ArticleForm(instance=seleted_article)
    if request.method == 'POST':
        data = request.POST.copy()
        article_form = ArticleForm(data, instance=seleted_article)
        if article_form.is_valid():
            article = article_form.save(commit=False)
            article.account_id = seleted_article.account_id
            article.written_date = seleted_article.written_date
            article.save()
            return HttpResponseRedirect(reverse("view_single_article", args=[article.id]))
        else:
            message = u'Có lỗi ở dữ liệu nhập vào.'

    context = RequestContext(request)
    categories = Category.objects.all().order_by("order", "name")
    cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
    headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
    return_headlines = u".....".join([headline.title for headline in headlines])
    return render_to_response('edit_article.html',
            {'message': message,
             'form': article_form,
             'menu' : cat_menu,
             'categories' : categories,
             'headlines' : return_headlines},
        context_instance=context)


def view_single_article(request, article_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    try:
        seleted_article = Article.objects.get(id=article_id, status = 1)
    except Exception as e:
        raise Exception("Bad request Exception")
    context = RequestContext(request)
    categories = Category.objects.all().order_by("order", "name")
    cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
    headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
    return_headlines = u".....".join([headline.title for headline in headlines])
    return render_to_response('single_article.html', {'post': seleted_article, 'categories' : categories, 'menu' : cat_menu, 'headlines' : return_headlines}, context_instance=context)


def delete_article(request, article_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    try:
        seleted_article = Article.objects.get(id=article_id, status = 1)
    except Exception as e:
        raise Exception("Bad request Exception")
    seleted_article.status = 2
    seleted_article.save()
    return HttpResponseRedirect(reverse('index'))


def view_specific_day(request, day, month, year):
    request_date = date(int(year), int(month), int(day))
    articles = Article.objects.filter(post_date__year = request_date.year,
        post_date__month = request_date.month,
        post_date__day = request_date.day,
        status = 1, post_date__lt = datetime.now()).order_by('-post_date')
    paginator = Paginator(articles, QUOTA) # Show QUOTA posts per page

    page = request.GET.get('page')
    try:
        return_posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        return_posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        return_posts = paginator.page(paginator.num_pages)
    context = RequestContext(request)
    categories = Category.objects.all().order_by('order')
    cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
    headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
    return_headlines = u".....".join([headline.title for headline in headlines])
    return render_to_response('posts_in_specific_day.html', {'posts': return_posts, 'headlines' : return_headlines, 'date' : request_date,'menu' : cat_menu, 'categories' : categories}, context_instance=context)

def view_in_categories(request, categories):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    categories = re.findall(r'\d+',categories)
    list_artiles = []
    sub_menu = (len(categories) == 1)
    if sub_menu:
        if int(categories[0]):
            child_category = Category.objects.get(id = int(categories[0]))
            category = child_category.parent
            if not category:
                category = child_category
            children = Category.objects.filter(parent = category)
            children_id = [int(child.id) for child in children]
            children_id.append(int(category.id))
            cat_menu = Category.objects.filter(id__in = children_id).order_by('order')
        else:
            cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
    else:
        sub_menu = True
        category = Category.objects.get(id = int(categories[0]))
        children = Category.objects.filter(parent = category)
        children_id = [int(child.id) for child in children]
        children_id.append(int(categories[0]))

        for cat in categories:
            if not (int(cat) in children_id):
                sub_menu = False
        if sub_menu:
            cat_menu = Category.objects.filter(id__in = children_id).order_by('order')
        else:
            cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')

    for category_id in categories:
        if int(category_id):
            category = Category.objects.get(id = int(category_id))
            articles = category.article_set.filter(status = 1, post_date__lt = datetime.now() ).order_by('-post_date')
        else:
            articles = Article.objects.filter(status = 1, category_id = None, post_date__lt = datetime.now()).order_by('-post_date')
        list_artiles += articles

    paginator = Paginator(list_artiles, QUOTA) # Show QUOTA posts per page

    page = request.GET.get('page')
    try:
        return_posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        return_posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        return_posts = paginator.page(paginator.num_pages)
    context = RequestContext(request)
    categories = Category.objects.all().order_by('order')
    headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
    return_headlines = u".....".join([headline.title for headline in headlines])
    return render_to_response('index.html', {'posts': return_posts, 'categories' : categories, 'menu' : cat_menu, 'headlines' : return_headlines}, context_instance=context)

def view_by_account(request, account_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    if int(account_id) > 0:
        author = User.objects.get(id = account_id)
    else:
        author = None
    articles = Article.objects.filter(account_id=author,
        status = 1, post_date__lt = datetime.now()).order_by('-post_date')
    paginator = Paginator(articles, QUOTA) # Show QUOTA posts per page

    page = request.GET.get('page')
    try:
        return_posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        return_posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        return_posts = paginator.page(paginator.num_pages)
    context = RequestContext(request)
    categories = Category.objects.all().order_by('order')
    cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
    headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
    return_headlines = u".....".join([headline.title for headline in headlines])
    return render_to_response('index.html', {'posts': return_posts, 'categories' : categories, 'menu' : cat_menu, 'headlines' : return_headlines}, context_instance=context)

def headline(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index'))
    message = ''
    headline_form = HeadlineForm()
    if request.method == 'POST':
        data = request.POST.copy()
        headline_form = HeadlineForm(data=data)
        if headline_form.is_valid():
            headline_form.save()
            headline_form = HeadlineForm()
            message = u'Thêm thành công.'
        else:
            message = u'Có lỗi ở dữ liệu nhập vào.'
    headlines = Headline.objects.all().order_by("-post_date", "-show_date")
    paginator = Paginator(headlines, QUOTA_HEADLINE) # Show QUOTA posts per page
    page = request.GET.get('page')
    current_headlines = None
    try:
        current_headlines = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        return_posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        return_posts = paginator.page(paginator.num_pages)

    context = RequestContext(request)
    categories = Category.objects.all().order_by("order", "name")
    cat_menu = Category.objects.filter(show_in_menu = True).order_by('order')
    headlines = Headline.objects.filter(show_date__lt = datetime.now()).order_by('show_date')
    return_headlines = u".....".join([headline.title for headline in headlines])
    return render_to_response('new_headline.html',
            {'message': message,
             'current_headlines' : current_headlines,
             'headlines' : return_headlines,
             'categories' : categories,
             'menu' : cat_menu,
             'form': headline_form},
        context_instance=context)